/*
 *  DebugFuncs.cpp
 *  Brawlers
 *
 *  Created by Leroy Ketelaars on 9/29/09.
 *  Copyright 2009 Zombies on Fire. All rights reserved.
 *
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

#include "SDL.h"
#include "SDL_ttf/SDL_ttf.h"
#include "DebugFuncs.h"

void DrawCollisionrect(int x, int y, int w, int h, SDL_Surface* scrn)
{
	for(int ty = y; ty < y + h; ty++)
	{
		putpixel(scrn, x, ty, 0xff00ff);
		putpixel(scrn, x + 1, ty, 0xff00ff);
		
		putpixel(scrn, (x + w) - 1, ty, 0xff00ff);
		putpixel(scrn, (x + w) - 2, ty, 0xff00ff);
		
	}
	for(int tx = x; tx < x + w; tx++)
	{
		putpixel(scrn, tx, y, 0xff00ff);
		putpixel(scrn, tx, (y + h) - 1, 0xff00ff);
		putpixel(scrn, tx, y + 1, 0xff00ff);
		putpixel(scrn, tx, (y + h) - 2, 0xff00ff);
	}
}

void DrawCollisionrect(BSRect* r, SDL_Surface* scrn)
{
	int rx = (int) r->x;
	int ry = (int) r->y;
	DrawCollisionrect(rx, ry, r->w, r->h, scrn);
}
void DrawCollisionrect(SDL_Rect* r, SDL_Surface* scrn)
{
	DrawCollisionrect(r->x, r->y, r->w, r->h, scrn);
}
bool SDLInit(QMView* v)
{
	if(v != NULL)
	{
		/* Initialize the SDL library */
		if ( SDL_Init(SDL_INIT_VIDEO) < 0 ) {
			fprintf(stderr, "Couldn't initialize SDL: %s\n",
					SDL_GetError());
			return false;
		}
		
		v->scrn = SDL_SetVideoMode(v->bounds.w, v->bounds.h, 0, SDL_SWSURFACE);
		if (v->scrn == NULL) {
			fprintf(stderr, "Couldn't set %d%d%d video mode: %s\n",
					v->bounds.w, v->bounds.h, 0, SDL_GetError());
			SDL_Quit();
			return false;
		}
		v->events = new SDL_Event();
		/* init sdl ttf */
		if(TTF_Init()==-1) 
		{
			printf("TTF_Init: %s\n", TTF_GetError());
			return false;
		}	
		SDL_WM_SetCaption("Brawlers | svn build 4, development", NULL);
		
	}
	return true;
}

//taken from SDL documentation
void putpixel(SDL_Surface *surface, int x, int y, Uint32 pixel)
{
    int bpp = surface->format->BytesPerPixel;
    /* Here p is the address to the pixel we want to set */
    Uint8 *p = (Uint8 *)surface->pixels + y * surface->pitch + x * bpp;
	
    switch(bpp) {
		case 1:
			*p = pixel;
			break;
			
		case 2:
			*(Uint16 *)p = pixel;
			break;
			
		case 3:
			if(SDL_BYTEORDER == SDL_BIG_ENDIAN) {
				p[0] = (pixel >> 16) & 0xff;
				p[1] = (pixel >> 8) & 0xff;
				p[2] = pixel & 0xff;
			} else {
				p[0] = pixel & 0xff;
				p[1] = (pixel >> 8) & 0xff;
				p[2] = (pixel >> 16) & 0xff;
			}
			break;
			
		case 4:
			*(Uint32 *)p = pixel;
			break;
    }
}
